package cn.swing.his.passport.service.impl;

import cn.swing.his.common.exception.HisServiceException;
import cn.swing.his.common.pojo.domain.HisAuthenticationInfo;
import cn.swing.his.common.web.ResponseCode;
import cn.swing.his.passport.pojo.domain.DoctorDetails;
import cn.swing.his.common.utils.JwtUtils;
import cn.swing.his.passport.service.IDoctorService;
import cn.swing.his.pojo.password.dto.DoctorLoginDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DoctorServiceImpl implements IDoctorService {
    @Autowired
    private DoctorDetailsServiceImpl doctorDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtUtils jwtUtils;

    // 处理登录，生成JWT
    @Override
    public String doLogin(DoctorLoginDTO doctorLoginDTO) {
        String jwt;
        DoctorDetails doctorDetails = (DoctorDetails) doctorDetailsService.loadUserByUsername(doctorLoginDTO.getTelephone());
        log.info("doctorDetails={}",doctorDetails);
        // 判断密码是否匹配
        if(!passwordEncoder.matches(doctorLoginDTO.getPassword(),doctorDetails.getPassword())){
            throw new HisServiceException(ResponseCode.PASSWORD_NOT_MATCH,"登录失败,密码不正确");
        }
        // 将自定义认证数据封装
        HisAuthenticationInfo doctorInfo = new HisAuthenticationInfo();
        List<GrantedAuthority> authorities = (List<GrantedAuthority>) doctorDetails.getAuthorities();
        log.info("authorities={}",authorities);
        List<String> authorityValues = new ArrayList<>();
        for (GrantedAuthority authority : authorities) {
            String value = authority.getAuthority();
            authorityValues.add(value);
        }
        doctorInfo.setId(doctorDetails.getId());
        doctorInfo.setTelephone(doctorDetails.getTelephone());
        doctorInfo.setPermissions(authorityValues);

        // 生成JWT
        jwt = jwtUtils.generateClaims(doctorInfo);
        return jwt;
    }
}
